<template>
  <div class="admin-info-container">
    <el-card class="info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
        </div>
      </template>
      
      <el-row :gutter="20">
        <!-- 左侧信息区域 -->
        <el-col :md="8">
          <div class="avatar-container">
            <el-avatar :size="120" :src="adminInfo.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'">
              <el-icon><UserFilled /></el-icon>
            </el-avatar>
            <h2 class="admin-name">{{ adminInfo.username }}</h2>
            <p class="admin-role">系统管理员</p>
            <p class="admin-profile">{{ adminInfo.profile || '暂无个人介绍' }}</p>
          </div>
        </el-col>
        
        <!-- 右侧详情区域 -->
        <el-col :md="16">
          <el-form :model="adminInfo" label-width="100px" class="admin-form">
            <el-form-item label="用户名">
              <el-input v-model="adminInfo.username" disabled />
            </el-form-item>
            
            <el-form-item label="性别">
              <el-radio-group v-model="adminInfo.gender" :disabled="!isEditing">
                <el-radio :label="0">男</el-radio>
                <el-radio :label="1">女</el-radio>
                <el-radio :label="2">保密</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="电子邮箱">
              <el-input v-model="adminInfo.email" :disabled="!isEditing" />
            </el-form-item>
            
            <el-form-item label="手机号码">
              <el-input v-model="adminInfo.phone" :disabled="!isEditing" />
            </el-form-item>
            
            <el-form-item label="个人介绍">
              <el-input v-model="adminInfo.profile" type="textarea" rows="3" :disabled="!isEditing" />
            </el-form-item>
            
            <el-form-item label="注册时间">
              <el-input v-model="adminInfo.created_at" disabled />
            </el-form-item>
            
            <el-form-item>
              <template v-if="!isEditing">
                <el-button type="primary" @click="startEditing">编辑信息</el-button>
                <el-button type="warning" @click="showChangePwdDialog">修改密码</el-button>
              </template>
              <template v-else>
                <el-button type="primary" @click="saveAdminInfo">保存</el-button>
                <el-button @click="cancelEditing">取消</el-button>
              </template>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 密码修改对话框 -->
    <el-dialog v-model="changePwdDialogVisible" title="修改密码" width="400px">
      <el-form :model="pwdForm" ref="pwdFormRef" label-width="100px" :rules="pwdRules">
        <el-form-item label="原密码" prop="old_password">
          <el-input 
            v-model="pwdForm.old_password" 
            :type="showPasswords.old_password ? 'text' : 'password'" 
            autocomplete="off" 
            placeholder="请输入原密码"
          >
            <template #suffix>
              <el-icon 
                class="password-eye" 
                @click="showPasswords.old_password = !showPasswords.old_password"
              >
                <eye v-if="showPasswords.old_password" />
                <eye-slash v-else />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="新密码" prop="new_password">
          <el-input 
            v-model="pwdForm.new_password" 
            :type="showPasswords.new_password ? 'text' : 'password'" 
            autocomplete="off" 
            placeholder="请输入新密码"
          >
            <template #suffix>
              <el-icon 
                class="password-eye" 
                @click="showPasswords.new_password = !showPasswords.new_password"
              >
                <eye v-if="showPasswords.new_password" />
                <eye-slash v-else />
              </el-icon>
            </template>
          </el-input>
          <div class="password-strength" v-if="pwdForm.new_password">
            <span>密码强度:</span>
            <el-progress 
              :percentage="passwordStrength === 'weak' ? 33 : passwordStrength === 'medium' ? 66 : 100" 
              :status="passwordStrength === 'weak' ? 'exception' : passwordStrength === 'medium' ? 'warning' : 'success'"
              :stroke-width="8"
            />
            <span class="strength-text" :class="passwordStrength">
              {{ passwordStrength === 'weak' ? '弱' : passwordStrength === 'medium' ? '中' : '强' }}
            </span>
          </div>
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirm_password">
          <el-input 
            v-model="pwdForm.confirm_password" 
            :type="showPasswords.confirm_password ? 'text' : 'password'" 
            autocomplete="off" 
            placeholder="请再次输入新密码"
          >
            <template #suffix>
              <el-icon 
                class="password-eye" 
                @click="showPasswords.confirm_password = !showPasswords.confirm_password"
              >
                <eye v-if="showPasswords.confirm_password" />
                <eye-slash v-else />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="changePwdDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitChangePwd" :loading="pwdLoading">确认修改</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { UserFilled, Eye, EyeSlash } from '@element-plus/icons-vue'
import { getAdminInfo, updateAdminInfo, changePassword } from '@/api'
import { useRouter } from 'vue-router'

const router = useRouter()

// 管理员信息
const adminInfo = ref({
  id: 0,
  username: '',
  gender: 2, // 0表示男，1表示女，2表示保密
  email: '',
  phone: '',
  profile: '',
  avatar: '',
  created_at: ''
})

// 编辑状态
const isEditing = ref(false)
const originalInfo = ref({})

// 开始编辑
const startEditing = () => {
  originalInfo.value = JSON.parse(JSON.stringify(adminInfo.value))
  isEditing.value = true
}

// 取消编辑
const cancelEditing = () => {
  adminInfo.value = JSON.parse(JSON.stringify(originalInfo.value))
  isEditing.value = false
}

// 保存管理员信息
const saveAdminInfo = async () => {
  try {
    await updateAdminInfo(adminInfo.value)
    
    ElMessage.success('个人信息更新成功')
    isEditing.value = false
    
    // 更新原始数据，保持同步
    originalInfo.value = JSON.parse(JSON.stringify(adminInfo.value))
  } catch (error) {
    console.error('更新个人信息失败:', error)
    ElMessage.error('更新个人信息失败')
  }
}

// 获取管理员信息
const fetchAdminInfo = async () => {
  try {
    const response = await getAdminInfo()
    
    // 更新管理员信息，确保性别字段为数字类型
    const info = response.data.data
    info.gender = Number(info.gender)
    adminInfo.value = info
    
    // 初始化originalInfo，用于取消编辑时恢复
    originalInfo.value = JSON.parse(JSON.stringify(info))
  } catch (error) {
    console.error('获取管理员信息失败:', error)
    ElMessage.error('获取管理员信息失败')
  }
}

// 修改密码相关
const changePwdDialogVisible = ref(false)
const pwdLoading = ref(false)
const pwdForm = ref({
  old_password: '',
  new_password: '',
  confirm_password: ''
})
const pwdFormRef = ref(null)

// 显示密码控制
const showPasswords = ref({
  old_password: false,
  new_password: false,
  confirm_password: false
})

// 显示修改密码对话框
const showChangePwdDialog = () => {
  changePwdDialogVisible.value = true
  pwdForm.value = {
    old_password: '',
    new_password: '',
    confirm_password: ''
  }
  
  // 重置所有显示密码状态为隐藏
  showPasswords.value = {
    old_password: false,
    new_password: false,
    confirm_password: false
  }
}

// 密码强度计算
const passwordStrength = computed(() => {
  const password = pwdForm.value.new_password
  if (!password) return ''
  
  const hasLetters = /[a-zA-Z]/.test(password)
  const hasNumbers = /\d/.test(password)
  const hasSpecialChars = /[!@#$%^&*()_+\-=[{};':"\\|,.<>/?]/.test(password)
  
  if (password.length < 6) return 'weak'
  if (password.length >= 8 && hasLetters && hasNumbers && hasSpecialChars) return 'strong'
  return 'medium'
})

// 验证函数 - 新密码不能与原密码相同
const validateNewPassword = (rule, value, callback) => {
  if (value === pwdForm.value.old_password) {
    callback(new Error('新密码不能与原密码相同'))
  } else {
    callback()
  }
}

// 验证函数 - 确认新密码
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== pwdForm.value.new_password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 密码规则
const pwdRules = {
  old_password: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
    { validator: validateNewPassword, trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 提交修改密码
const submitChangePwd = () => {
  if (!pwdFormRef.value) return
  
  pwdFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    pwdLoading.value = true
    try {
      // 调用修改密码API
      await changePassword({
        old_password: pwdForm.value.old_password,
        new_password: pwdForm.value.new_password
      })
      
      ElMessage.success('密码修改成功，请重新登录')
      changePwdDialogVisible.value = false
      
      // 退出登录并跳转到登录页
      localStorage.removeItem('adminToken')
      router.push('/admin/login')
    } catch (error) {
      console.error('密码修改失败:', error)
      ElMessage.error('密码修改失败')
    } finally {
      pwdLoading.value = false
    }
  })
}

// 页面加载时获取信息
onMounted(() => {
  fetchAdminInfo()
})
</script>

<style scoped>
.admin-info-container {
  padding: 20px;
}

.info-card {
  margin-bottom: 20px;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.admin-name {
  margin-top: 15px;
  margin-bottom: 5px;
  font-size: 1.5rem;
}

.admin-role {
  color: #909399;
  margin-top: 5px;
  margin-bottom: 10px;
}

.admin-profile {
  color: #606266;
  text-align: center;
  padding: 10px;
  font-size: 0.9rem;
}

.admin-form {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
}

/* 密码相关样式 */
.password-eye {
  cursor: pointer;
  color: #909399;
  transition: all 0.3s;
}

.password-eye:hover {
  color: #409EFF;
}

.password-strength {
  display: flex;
  align-items: center;
  margin-top: 8px;
  font-size: 12px;
  color: #606266;
}

.password-strength .el-progress {
  margin: 0 8px;
  flex: 1;
}

.strength-text {
  width: 20px;
  text-align: center;
}

.strength-text.weak {
  color: #f56c6c;
}

.strength-text.medium {
  color: #e6a23c;
}

.strength-text.strong {
  color: #67c23a;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}
</style> 